package ces.lawsuit.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;

import ces.lawsuit.util.AppUtil;
import ces.lawsuit.util.Util;

public class BaseModel<T> extends Model {
	
	
	protected static String add;
	protected static String edit;
	protected static String dataGrid;
    
	@Override
	public boolean save() {
		if(StrKit.isBlank(getStr("id")))
			set("id", AppUtil.generateId());
		return super.save();
	}
	private int[] batchExecUpdate(String sql, Object[]... paramss) throws SQLException {
		Config config = getConfig();
		Table table = getTable();
		if (paramss == null) {
			paramss = new Object[0][0];
		}
		Connection conn = null;
		PreparedStatement pst = null;
		int[] rows = null;
		try {
			conn = config.getConnection();
			if (config.getDialect().isOracle()) {
				pst = conn.prepareStatement(sql.toString(), table.getPrimaryKey() );
			} else {
				pst = conn.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
			}
			for (Object[] params : paramss) {
				config.getDialect().fillStatement(pst, params);
				pst.addBatch();
			}
			rows = pst.executeBatch();
		} finally {
			config.close(pst, conn);
		}
		return rows;
	}
	/**
	 *设置主键值 
	 **/
	public void setPrimaryValue(String field){
		this.set(field,AppUtil.generateId());
	}
    /**
     *@param modelList 要设值的model集合
     *
     **/
	public void setPrimaryValues(List<? extends BaseModel> modelList, String field) {
		for (BaseModel model : modelList) {
			if (Util.isNull(model.get(field))) {
				model.set(field, AppUtil.generateId());
			}
		}
	}
	/**默认主键为id*/
	public void setPrimaryValues(List<? extends BaseModel> modelList){
		setPrimaryValues(modelList, "id");
	}
	public void batchSave(List<T> beanList) {
		if (beanList != null && beanList.size() > 0) {
			Config config = getConfig();
			Table table = getTable();
			try {
				String sql = null;
				List<Object[]> paramsList = new ArrayList<Object[]>();
				for (T bean : beanList) {
					StringBuilder sb = new StringBuilder();
					List<Object> paras = new ArrayList<Object>();
					config.getDialect().forModelSave(table, ((BaseModel)bean).getAttrs(), sb, paras);
					if (sql == null) {
						sql = sb.toString();
					}
					paramsList.add(paras.toArray());
				}
				Object[][] paramss = new Object[paramsList.size()][];
				int i = 0;
				for (Object[] oo : paramsList) {
					paramss[i++] = oo;
				}
				batchExecUpdate(sql, paramss);
			} catch (Exception e) {
				throw new ActiveRecordException(e);
			}
		}
	}
}
